import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'package:get/get.dart';
import 'package:xiaomi_shop/app/api/api.dart';
import 'package:xiaomi_shop/app/modules/cart/controllers/cart_controller.dart';
import 'package:xiaomi_shop/app/modules/shop/controllers/shop_detail_controller.dart';
import 'package:xiaomi_shop/app/modules/shop/views/shop_detail_info_view.dart';
import 'package:xiaomi_shop/app/modules/shop/views/shop_detail_recommend_view.dart';
import 'package:xiaomi_shop/app/modules/shop/views/shop_detail_web_view.dart';
import 'package:xiaomi_shop/app/services/cartService.dart';
import 'package:xiaomi_shop/app/services/screenAdapter.dart';
import 'package:xiaomi_shop/app/services/userService.dart';
import 'package:xiaomi_shop/app/services/xhttp.dart';
import 'package:xiaomi_shop/models/shopAttrItemModel.dart';

class ShopDetailView extends GetView<ShopDetailController> {
  const ShopDetailView({Key? key}) : super(key: key);

  _appBar(BuildContext context) {
    return Positioned(
      top: 0,
      left: 0,
      right: 0,
      child: Obx(() => AppBar(
            leading: IconButton(
                iconSize: ScreenAdapter.width(60),
                alignment: Alignment.center,
                style: ButtonStyle(
                    backgroundColor: MaterialStatePropertyAll(Colors.black
                        .withOpacity(controller.opcity.value == 1 ? 0 : 0.5)),
                    foregroundColor: MaterialStatePropertyAll(
                        controller.opcity.value == 1
                            ? Colors.black
                            : Colors.white)),
                onPressed: () {
                  Get.back();
                },
                icon: const Icon(Icons.arrow_back_ios_new_outlined)),
            actions: [
              IconButton(
                  iconSize: ScreenAdapter.width(60),
                  alignment: Alignment.center,
                  style: ButtonStyle(
                      backgroundColor: MaterialStatePropertyAll(Colors.black
                          .withOpacity(controller.opcity.value == 1 ? 0 : 0.5)),
                      foregroundColor: MaterialStatePropertyAll(
                          controller.opcity.value == 1
                              ? Colors.black
                              : Colors.white)),
                  onPressed: () {},
                  icon: const Icon(Icons.ios_share_outlined)),
              IconButton(
                  iconSize: ScreenAdapter.width(60),
                  alignment: Alignment.center,
                  style: ButtonStyle(
                      backgroundColor: MaterialStatePropertyAll(Colors.black
                          .withOpacity(controller.opcity.value == 1 ? 0 : 0.5)),
                      foregroundColor: MaterialStatePropertyAll(
                          controller.opcity.value == 1
                              ? Colors.black
                              : Colors.white)),
                  onPressed: () {
                    showMenu(
                        color: Colors.black87.withOpacity(0.8),
                        context: context,
                        position: RelativeRect.fromLTRB(
                            ScreenAdapter.width(800),
                            ScreenAdapter.height(140) +
                                ScreenUtil().statusBarHeight,
                            ScreenAdapter.width(20),
                            0),
                        items: [
                          PopupMenuItem(
                              child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            children: [
                              const Icon(
                                Icons.home,
                                color: Colors.white,
                              ),
                              Text(
                                "首页",
                                style: TextStyle(
                                    color: Colors.white,
                                    fontSize: ScreenAdapter.fontSize(38)),
                              )
                            ],
                          )),
                          PopupMenuItem(
                              child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            children: [
                              const Icon(
                                Icons.message,
                                color: Colors.white,
                              ),
                              Text(
                                "消息",
                                style: TextStyle(
                                    color: Colors.white,
                                    fontSize: ScreenAdapter.fontSize(38)),
                              )
                            ],
                          )),
                          PopupMenuItem(
                              child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            children: [
                              const Icon(
                                Icons.star,
                                color: Colors.white,
                              ),
                              Text(
                                "收藏",
                                style: TextStyle(
                                    color: Colors.white,
                                    fontSize: ScreenAdapter.fontSize(38)),
                              )
                            ],
                          ))
                        ]);
                  },
                  icon: const Icon(Icons.more_horiz_outlined)),
            ],
            title: Opacity(
              opacity: controller.opcity.value,
              child: Container(
                width: ScreenAdapter.width(400),
                height: ScreenAdapter.height(100),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: controller.segments.map((e) {
                    var index = controller.segments.indexOf(e);
                    return InkWell(
                      onTap: () {
                        controller.selectSegmentIndex(index);
                      },
                      child: Column(
                        children: [
                          Text(
                            e,
                            style: TextStyle(
                                fontSize: ScreenAdapter.fontSize(50),
                                color: index == controller.segmentIndex.value
                                    ? Colors.red
                                    : Colors.black,
                                fontWeight:
                                    index == controller.segmentIndex.value
                                        ? FontWeight.bold
                                        : FontWeight.normal),
                          ),
                          Container(
                            width: ScreenAdapter.width(80),
                            height: ScreenAdapter.height(8),
                            color: index == controller.segmentIndex.value
                                ? Colors.red
                                : Colors.white,
                            margin:
                                EdgeInsets.only(top: ScreenAdapter.height(10)),
                          )
                        ],
                      ),
                    );
                  }).toList(),
                ),
              ),
            ),
            centerTitle: true,
            backgroundColor: Colors.white.withOpacity(controller.opcity.value),
            elevation: 0,
            scrolledUnderElevation: 0,
          )),
    );
  }

  _skuSheet(int type) async {
    // 判断是否登录
    bool loginState = await UserService.getUserLoginState();
    if (!loginState) {
      // 先去登录
      Get.toNamed("/phone-one-click-login");
      return;
    }

    Get.bottomSheet(
      GetBuilder<ShopDetailController>(
        init: controller,
        builder: (controller) {
          return Container(
            padding: EdgeInsets.all(ScreenAdapter.width(30)),
            color: Colors.white,
            child: Column(
              children: [
                Container(
                  height: ScreenAdapter.height(280),
                  child: Row(
                    children: [
                      AspectRatio(
                        aspectRatio: 1.0,
                        child: Image.network(
                          "${Api.basicUrl}/${controller.shopModel.value.pic}",
                          fit: BoxFit.cover,
                        ),
                      ),
                      SizedBox(
                        width: ScreenAdapter.width(30),
                      ),
                      Expanded(
                          child: Column(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text.rich(TextSpan(children: [
                            TextSpan(
                                text: "¥${controller.shopModel.value.price}",
                                style: TextStyle(
                                    color: Colors.deepOrange,
                                    fontSize: ScreenAdapter.fontSize(58),
                                    fontWeight: FontWeight.bold)),
                            WidgetSpan(
                                child: SizedBox(
                              width: ScreenAdapter.width(8),
                            )),
                            TextSpan(
                                text:
                                    "¥${controller.shopModel.value.old_price}",
                                style: TextStyle(
                                    color: Colors.black54,
                                    fontSize: ScreenAdapter.fontSize(40),
                                    decoration: TextDecoration.lineThrough))
                          ])),
                          Text(
                            "Redmi K70 12GB+512GB 墨羽",
                            style: TextStyle(
                                fontSize: ScreenAdapter.fontSize(40),
                                fontWeight: FontWeight.w500),
                          )
                        ],
                      ))
                    ],
                  ),
                ),
                Expanded(
                    child: ListView.builder(
                  itemCount: controller.attrList.length,
                  itemBuilder: (context, index) {
                    Map<String, dynamic> attr = controller.attrList[index];
                    String title = attr['title'];
                    List<ShopAttrItemModel> attrItems = attr['list'];
                    return Container(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            title,
                            style: TextStyle(
                                fontWeight: FontWeight.bold,
                                height: ScreenAdapter.height(10)),
                          ),
                          Wrap(
                            spacing: ScreenAdapter.width(24),
                            runSpacing: ScreenAdapter.width(24),
                            children: attrItems.map((ShopAttrItemModel model) {
                              return InkWell(
                                onTap: () {
                                  controller.selectedAttr(title, model.title!);
                                },
                                child: Chip(
                                  label: Text(model.title!),
                                  labelStyle: TextStyle(
                                      color: model.selected!
                                          ? Colors.white
                                          : Colors.black),
                                  backgroundColor: model.selected!
                                      ? Colors.red
                                      : Colors.grey.shade100,
                                  side: BorderSide.none,
                                  shape: RoundedRectangleBorder(
                                      side: BorderSide.none,
                                      borderRadius: BorderRadius.circular(20)),
                                ),
                              );
                            }).toList(),
                          )
                        ],
                      ),
                    );
                  },
                )),
                Container(
                  height: ScreenAdapter.height(160),
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          "数量",
                          style: TextStyle(
                              fontWeight: FontWeight.bold,
                              height: ScreenAdapter.height(10)),
                        ),
                        SizedBox(
                          width: ScreenAdapter.width(400),
                          height: ScreenAdapter.height(100),
                          child: Row(
                            children: [
                              IconButton(
                                  onPressed: () {
                                    if (controller.shopModel.value.buyNumber >
                                        1) {
                                      controller.shopModel.value.buyNumber--;
                                      controller.buyNumController.text =
                                          "${controller.shopModel.value.buyNumber}";
                                    }
                                  },
                                  icon: const Icon(Icons.remove)),
                              Expanded(
                                child: TextField(
                                  controller: controller.buyNumController,
                                  decoration: InputDecoration(
                                      filled: true,
                                      fillColor: Colors.grey.shade100,
                                      border: const OutlineInputBorder(
                                          borderSide: BorderSide.none)),
                                  keyboardType: TextInputType.number,
                                  textAlign: TextAlign.center,
                                  textAlignVertical: TextAlignVertical.top,
                                  style: TextStyle(
                                      fontSize: ScreenAdapter.fontSize(50)),
                                  onChanged: (value) {
                                    controller.shopModel.value.buyNumber =
                                        int.parse(value);
                                  },
                                ),
                              ),
                              IconButton(
                                  onPressed: () {
                                    if (controller.shopModel.value.buyNumber <
                                        99) {
                                      controller.shopModel.value.buyNumber++;
                                      controller.buyNumController.text =
                                          "${controller.shopModel.value.buyNumber}";
                                    }
                                  },
                                  icon: const Icon(Icons.add)),
                            ],
                          ),
                        ),
                      ]),
                ),
                Container(
                  height: ScreenAdapter.height(120),
                  width: ScreenAdapter.width(900),
                  margin: EdgeInsets.only(bottom: ScreenUtil().bottomBarHeight),
                  child: ElevatedButton(
                      style: const ButtonStyle(
                          backgroundColor:
                              MaterialStatePropertyAll(Colors.deepOrange),
                          padding: MaterialStatePropertyAll(EdgeInsets.zero)),
                      onPressed: () async {
                        if (type == 1) {
                          // 加入购物车
                          bool result = await CartService.addShop2Cart(
                              controller.shopModel.value);
                          if (result) {
                            CartController cartController =
                                Get.find<CartController>();
                            cartController.getCartData();
                            Toast.show("添加成功");
                            Get.back();
                          } else {
                            Toast.show("添加失败");
                          }
                        } else if (type == 2) {
                          // 立即支付
                          Get.toNamed("/checkout", arguments: {
                            "shopList": [controller.shopModel.value]
                          });
                        }
                      },
                      child: Text(
                        type == 1 ? "确认" : "立即购买",
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: ScreenAdapter.fontSize(38),
                            fontWeight: FontWeight.bold),
                      )),
                ),
              ],
            ),
          );
        },
      ),
      shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(top: Radius.circular(10))),
      clipBehavior: Clip.hardEdge,
    );
  }

  _content() {
    return Positioned(
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
      child: SingleChildScrollView(
          controller: controller.scrollController,
          child: Column(
            children: [
              ShopDetailInfoView(_skuSheet),
              ShopDetailWebView(_subSegment),
              ShopDetailRecommendView(),
            ],
          )),
    );
  }

  _bottomView() {
    return Container(
      height: ScreenUtil().bottomBarHeight + ScreenAdapter.height(160),
      padding: EdgeInsets.fromLTRB(
          ScreenAdapter.width(40),
          ScreenAdapter.width(20),
          ScreenAdapter.width(40),
          ScreenAdapter.width(20)),
      decoration: const BoxDecoration(
          color: Colors.white,
          border: Border(top: BorderSide(color: Colors.black12, width: 1.0))),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Column(
                children: [
                  Icon(
                    Icons.support_agent,
                    size: ScreenAdapter.width(60),
                    color: Colors.black54,
                  ),
                  Expanded(
                      child: Text(
                    "客服",
                    style: TextStyle(
                        color: Colors.black54,
                        fontSize: ScreenAdapter.fontSize(28)),
                  ))
                ],
              ),
              SizedBox(
                width: ScreenAdapter.width(60),
              ),
              Column(
                children: [
                  Icon(
                    Icons.favorite_border_outlined,
                    size: ScreenAdapter.width(60),
                    color: Colors.black54,
                  ),
                  Expanded(
                      child: Text(
                    "收藏",
                    style: TextStyle(
                        color: Colors.black54,
                        fontSize: ScreenAdapter.fontSize(28)),
                  ))
                ],
              ),
              SizedBox(
                width: ScreenAdapter.width(60),
              ),
              InkWell(
                  onTap: () {
                    Get.toNamed('/cart');
                  },
                  child: Column(
                    children: [
                      Icon(
                        Icons.shopping_cart_outlined,
                        size: ScreenAdapter.width(60),
                        color: Colors.black54,
                      ),
                      Expanded(
                          child: Text(
                        "购物车",
                        style: TextStyle(
                            color: Colors.black54,
                            fontSize: ScreenAdapter.fontSize(28)),
                      ))
                    ],
                  ))
            ],
          ),
          Container(
            margin: EdgeInsets.zero,
            padding: EdgeInsets.zero,
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(ScreenAdapter.height(60))),
            width: ScreenAdapter.width(560),
            height: ScreenAdapter.height(120),
            clipBehavior: Clip.hardEdge,
            child: Row(
              children: [
                TextButton(
                    style: ButtonStyle(
                        backgroundColor:
                            MaterialStatePropertyAll(Colors.amber.shade600),
                        foregroundColor: MaterialStatePropertyAll(Colors.white),
                        fixedSize: MaterialStatePropertyAll(Size(
                            ScreenAdapter.width(280),
                            ScreenAdapter.height(80))),
                        shape:
                            MaterialStatePropertyAll(RoundedRectangleBorder())),
                    onPressed: () {
                      _skuSheet(1);
                    },
                    child: Text(
                      "加入购物车",
                      style: TextStyle(
                          fontSize: ScreenAdapter.fontSize(38),
                          fontWeight: FontWeight.bold),
                    )),
                TextButton(
                    style: ButtonStyle(
                        backgroundColor:
                            MaterialStatePropertyAll(Colors.deepOrange),
                        foregroundColor: MaterialStatePropertyAll(Colors.white),
                        fixedSize: MaterialStatePropertyAll(Size(
                            ScreenAdapter.width(280),
                            ScreenAdapter.height(120))),
                        shape:
                            MaterialStatePropertyAll(RoundedRectangleBorder())),
                    onPressed: () {
                      _skuSheet(2);
                    },
                    child: Text(
                      "立即购买",
                      style: TextStyle(
                          fontSize: ScreenAdapter.fontSize(38),
                          fontWeight: FontWeight.bold),
                    )),
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget _subSegment() {
    return Obx(() => Container(
          color: Colors.white,
          child: Row(
            children: controller.subSegments.map((e) {
              var index = controller.subSegments.indexOf(e);
              return Expanded(
                  child: InkWell(
                      onTap: () {
                        controller.selectSubSegmentIndex(index);
                      },
                      child: Container(
                        alignment: Alignment.center,
                        height: ScreenAdapter.height(120),
                        child: Text(
                          e,
                          style: TextStyle(
                              color: index == controller.subSegmentIndex.value
                                  ? Colors.red
                                  : Colors.black,
                              fontSize: ScreenAdapter.fontSize(46),
                              fontWeight: FontWeight.w500),
                        ),
                      )));
            }).toList(),
          ),
        ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          _content(),
          _appBar(context),
          Positioned(
              left: 0,
              top: ScreenUtil().statusBarHeight + ScreenAdapter.height(118),
              right: 0,
              child: Obx(() => controller.showSubSegment.value
                  ? _subSegment()
                  : const Text("")))
        ],
      ),
      bottomNavigationBar: _bottomView(),
    );
  }
}
